package TopTen;

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.border.Border;

/**
 * 
 * @author jonatanprins
 * @version rc1
 *
 */
public class ProgressBar implements Runnable {
	/*
	 * Declaration of variables
	 */
	private JFrame f;
	private Container content;
	private JProgressBar progressBar;
	private TopTenGenerator generator;
	private JLabel label;

	/**
	 * Constructor
	 * @param Takes the top ten generator
	 */
	public ProgressBar(TopTenGenerator generator) {
		this.generator = generator;
		new Thread(this).start();
	}
	
	/**
	 * Initializes a new progress bar
	 */
	private void init() {
		this.f = new JFrame("Cloud Analyzers");
		this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.content = f.getContentPane();
		this.label = new JLabel("");
		this.progressBar = new JProgressBar();
		this.progressBar.setStringPainted(true);
		Border border = BorderFactory.createTitledBorder("Generating...");
		this.progressBar.setBorder(border);
		this.content.add(progressBar, BorderLayout.NORTH);
		this.content.add(label, BorderLayout.SOUTH);

		this.f.setSize(300, 100);
		this.f.setVisible(true);
	}

	/**
	 * disposes the progress window
	 */
	private void close() {
		try {
			f.dispose();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/**
	 * Sets the values of the progress bar
	 * @param value current %
	 * @param process what it's currently doing
	 */
	private void setValue(Integer value, String process) {
		try {
			progressBar.setValue(value);
			label.setText(process);
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/**
	 * Run method
	 */
	@Override
	public void run() {
		while (true) {
			this.init();
			while (generator.progress < 101) {
				try {
					Thread.sleep(100);
				} catch (Exception e) {
					System.out.println(e);
				}
				this.setValue(generator.progress, generator.currentProcess);
				generator.changeElapsed();
			}
			try {
				Thread.sleep(10000);
			} catch (Exception e) {
				System.out.println(e);
			}
			
			this.close();

			break;
		}

	}
}
